/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.repairsystem.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.view.DownloadView;
import ssn.common.web.CommonController;
import ssn.currentsystem.service.CurrentSystemService;
import ssn.repairsystem.service.RepairSystemService;
import ssn.repairsystem.vo.RepairSystemVO;
import ssn.servicearea.service.ServiceAreaService;
import ssn.servicearea.vo.ServiceAreaVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2013.10.09           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings({"rawtypes","unchecked"})
@Controller
public class RepairSystemController extends CommonController{
	
    @Resource(name = "repairSystemService")
    private RepairSystemService repairSystemService;
    
    @Resource(name = "serviceareaService")
    private ServiceAreaService serviceareaService;
    
    @Resource(name = "currentSystemService")
    private CurrentSystemService currentSystemService;

    /**
	 * 글 목록을 조회한다(부모 리스트) 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/repairSystem/repairServiceareaList.do")
    public String serviceAreaList(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	if(!loginSessionInfo.get().isAdmin()){
    		return "redirect:/repairSystem/repairSystemList.do";
    	}
    	Map resultMap = serviceareaService.selectServiceAreaList(serviceareaVO);
    	List resultList = (List)resultMap.get("resultList");
    	serviceareaVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("zoneList", resultMap.get("zoneList"));
    	model.addAttribute("serviceareaVO", serviceareaVO);
        
        return "/repairSystem/repairServiceareaList";
    }
    
    /**
     * 글 목록을 조회한다 시설 품명 조회 
     * @param 
     * @param model
     * @return 
     * @exception Exception
     */
    @RequestMapping(value="/repairSystem/searchCurrentSystem.do")
    public String searchCurrentSystem(@RequestParam(value="sysName", required=false) String sysName,
    			@RequestParam(value="areaKey", required=false) String areaKey,	
    			ModelMap model) throws Exception {
    	
    	if(!loginSessionInfo.get().isAdmin()){
    		areaKey = loginSessionInfo.get().getSsa_area_key();
    	}else{
    		if(EgovStringUtil.isEmpty(areaKey)){
    			throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    		}
    	}
    	Map paramMap = new HashMap();
    	paramMap.put("sysName", sysName);
    	paramMap.put("areaKey", areaKey);
    	
    	List resultList = currentSystemService.selectSearchCurrentSystem(paramMap);
    	
    	model.addAttribute("paramMap", paramMap);
    	model.addAttribute("resultList", resultList);
    	
    	return "/repairSystem/searchCurrentSystem";
    }
    
    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/repairSystem/repairSystemList.do")
    public String repairSystemList(@ModelAttribute("repairSystemVO") RepairSystemVO repairSystemVO,
    			ModelMap model) throws Exception {
    	
    	if(!loginSessionInfo.get().isAdmin()){
    		repairSystemVO.setSrs_area_key(loginSessionInfo.get().getSsa_area_key());
    	}else{
    		if(EgovStringUtil.isEmpty(repairSystemVO.getSrs_area_key())){
    			return "redirect:/repairSystem/repairServiceareaList.do";
    		}
    	}
    	Map resultMap = repairSystemService.selectRepairSystemList(repairSystemVO);
    	List resultList = (List)resultMap.get("resultList");
    	repairSystemVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("repairSystemVO", repairSystemVO);
        
        return "/repairSystem/repairSystemList";
    }
    
    
    /**
     * 글쓰기 수정폼
     * @param repairSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/repairSystem/repairSystemWriteForm.do")
    public String repairSystemWriteForm(@ModelAttribute("repairSystemVO") RepairSystemVO repairSystemVO,
    			ModelMap model) throws Exception {
    	if(EgovStringUtil.isNotEmpty(repairSystemVO.getSrs_repr_key())){
    		RepairSystemVO resultVO = repairSystemService.selectRepairSystemInfo(repairSystemVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(repairSystemVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    	}else{
    		model.addAttribute("resultVO", repairSystemVO);
    	}
        return "/repairSystem/repairSystemWriteForm";
    }
    
    
    
    @RequestMapping(value="/repairSystem/repairSystemSave.do", method=RequestMethod.GET)
    public String repairSystemWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/repairSystem/repairSystemWriteForm.do";
    }
    
    /**
     * 저장/수정
     * @param repairSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/repairSystem/repairSystemSave.do", method=RequestMethod.POST)
    public String repairSystemSave(@ModelAttribute("repairSystemVO") @Valid RepairSystemVO repairSystemVO, BindingResult bindingResult, RedirectAttributes redirectAttr) throws Exception {
    	if(bindingResult.hasErrors()){
			for(FieldError error :  bindingResult.getFieldErrors()){
				redirectAttr.addFlashAttribute("error_"+error.getField(), error.getDefaultMessage());
    		}
			redirectAttr.addFlashAttribute("repairSystemVO", repairSystemVO);
			return "redirect:/repairSystem/repairSystemWriteForm.do";
		}
		if(EgovStringUtil.isNotEmpty(repairSystemVO.getSrs_repr_key())){
			repairSystemService.updateRepairSystemInfo(repairSystemVO);
		}else{
			repairSystemService.insertRepairSystemInfo(repairSystemVO);
		}
		redirectAttr.addFlashAttribute("msg", "저장 되었습니다.");
		redirectAttr.addAttribute("srs_area_key", repairSystemVO.getSrs_area_key());
    	redirectAttr.addAttribute("srs_repr_key", repairSystemVO.getSrs_repr_key());
    	redirectAttr.addAttribute("pageIndex", repairSystemVO.getPageIndex());
    	return "redirect:/repairSystem/repairSystemWriteForm.do";
    }
    
    /**
     * 삭제
     * @param repairSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/repairSystem/repairSystemDelete.do", method=RequestMethod.POST)
    public ModelAndView repairSystemDelete(@ModelAttribute("repairSystemVO") RepairSystemVO repairSystemVO) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/repairSystem/repairSystemList.do"));
		if(EgovStringUtil.isNotEmpty(repairSystemVO.getSrs_repr_key())){
			repairSystemService.deleteRepairSystemInfo(repairSystemVO);
		}else{
			throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
		}
    	mav.addObject("srs_area_key", repairSystemVO.getSrs_area_key());
    	mav.addObject("pageIndex", repairSystemVO.getPageIndex());
    	return mav;
    }
}
